import random
from openpyxl import load_workbook, Workbook
import re
import os
import time
import ProgressBar

wb = Workbook()
ws = wb.active
pattern = r"\.xlsx$"

path = input('输入你的单词表文件路径：')
while True:
    if re.search(pattern, path) is None:
        print("文件路径不符合规则")
    else:
        if os.path.exists(path):
            try:
                wb = load_workbook(path)
                ws = wb.active
                print('打开成功')
                break
            except:
                print('该文件可能受损，请重试')
        else:
            print("文件不存在")

print('这个工作簿有以下工作表', wb.sheetnames)
print('当前准备读取的是', ws.title)
input('请确保你的单词在表格的A列上（第一列）\n汉语意思在B列上（第二列）\n按回车键以继续...')
print(f'\n该表格中有{ws.max_row}个单词')

print('准备读取单词...')
pb = ProgressBar.ProgressBar(from_=1, to=ws.max_row, bar_length=10, what='正在读取...')
wordlist = []
for i in range(1, ws.max_row + 1):
    wordlist.append([ws.cell(i, 1).value, ws.cell(i, 2).value])
    pb.update(add=1)
    pb.show()
    time.sleep(0.25)

print('\n单词导入已完成')
print('请审核:')
for i in wordlist:
    print(i)

input('准备小测，按回车开始')
os.system('cls' if os.name == 'nt' else 'clear')

answer = []
user_answer = []

for i in range(1, len(wordlist) + 1):
    which = random.randint(1, len(wordlist))
    answer.append(wordlist[which - 1][0])
    user_answer.append(input(f'{wordlist[which - 1][1]}：'))
    wordlist.pop(which - 1)

print('小测结束，请查看结果')
print('[正确答案]-[你的答案]-[是否正确]')
for i in range(1, len(answer) + 1):
    print(f'{i}. {answer[i - 1]} - {user_answer[i - 1]} {'正确' if answer[i - 1] == user_answer[i - 1] else '错误'}')
